package com.heo.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heo.pojo.CommandResult;
import com.heo.pojo.DeviceChannelEntity;
import com.heo.pojo.DeviceInfoEntity;
import com.heo.pojo.OrgInfoEntity;
import com.heo.pojo.req.UpdateDevicePara;
import com.heo.pub.SysConfig;
import com.heo.service.DeviceChannelService;
import com.heo.service.DeviceInfoService;
import com.heo.service.OrgInfoService;
import com.heo.util.EncryptHelper;

/**
 * @author chichi
 */

@Controller
@Scope("singleton") // 1、为了性能。2、不需要多例。只要controller中不定义属性，那么单例完全是安全的。
@RequestMapping("/")
public class UpdateController extends BaseController
{
  private static Logger log = Logger.getLogger(UpdateController.class);

  @Resource(name = "orgInfoService")
  private OrgInfoService orgInfoService;

  @Resource(name = "deviceInfoService")
  private DeviceInfoService deviceInfoService;

  @Resource(name = "deviceChannelService")
  private DeviceChannelService deviceChannelService;

  /**
   * 更新设备参数信息
   * 
   * @param session
   * @param request
   * @param QueryStatPara
   * @return
   */
  @ResponseBody
  @RequestMapping(value = "/update_device_para.do", method = { RequestMethod.POST })
  public JSONObject queryDevice(HttpSession session, HttpServletRequest request, @RequestBody UpdateDevicePara updateDevicePara)
  {
    try
    {
      log.debug("[更新设备信息]收到请求参数：" + updateDevicePara.toString());

      // 校验参数
      HashMap<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("appId", updateDevicePara.getAppId());
      paraMap.put("appSecret", updateDevicePara.getAppSecret());
      List<OrgInfoEntity> orgList = orgInfoService.listByMap(paraMap, "listByAppId");
      if (orgList == null || orgList.size() != 1)
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }
      if (orgList == null || orgList.size() != 1)
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }
      // 判断appid是否合法
      if (!(orgList.get(0).getAppId().equals(updateDevicePara.getAppId()) && orgList.get(0).getAppSecret().equals(updateDevicePara.getAppSecret())))
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }

      String deviceImeis = updateDevicePara.getDeviceImeis();
      if (StringUtils.isEmpty(deviceImeis) || deviceImeis.length() == 0 || deviceImeis.split(",").length == 0)
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.PARA_ERROR, CommandResult.PublicResultMsg.PARA_ERROR);
        return JSON.parseObject(commandResult.toString());
      }
      // 先去找下需要更新的这些设备，是否有不存在的数据，如果有不存在的，那么就新增一条设备的记录
      List<String> list = java.util.Arrays.asList(deviceImeis.split(","));
      for (int i = 0; i < list.size(); i++)
      {
        String deviceImei = list.get(i);
        DeviceInfoEntity entity = deviceInfoService.getByKey(deviceImei);
        if (entity == null)
        {
          entity = new DeviceInfoEntity();
          entity.setDeviceImei(deviceImei);
          entity.setCreateTime(new Date());
          entity.setOrgId(orgList.get(0).getOrgId());
          entity.setAnswerTimeout(updateDevicePara.getDeviceInfo().getAnswerTimeout());
          entity.setAppendCommand(updateDevicePara.getDeviceInfo().getAppendCommand());
          entity.setDebugMode(updateDevicePara.getDeviceInfo().getDebugMode());
          entity.setDeviceChannelNum(1);// 默认都是1个通道，在批量改通道的接口里，去处理通道数量的配置问题
          entity.setDevicePassword(null);// 新增的时候一定是空
          entity.setHeartInterval(updateDevicePara.getDeviceInfo().getHeartInterval());
          entity.setInputChannelIdleStateLevel(updateDevicePara.getDeviceInfo().getInputChannelIdleStateLevel());
          entity.setOutConfirmPulseType(updateDevicePara.getDeviceInfo().getOutConfirmPulseType());
          entity.setOutPutCoinPulseType(updateDevicePara.getDeviceInfo().getOutPutCoinPulseType());
          entity.setResendMode(updateDevicePara.getDeviceInfo().getResendMode());
          entity.setRetryCount(updateDevicePara.getDeviceInfo().getRetryCount());
          entity.setSocketMode(updateDevicePara.getDeviceInfo().getSocketMode());
          entity.setGpsCheck(updateDevicePara.getDeviceInfo().getGpsCheck());
          entity.setDeviceModelId(updateDevicePara.getDeviceInfo().getDeviceModelId());
          entity.setDeviceStatus(0);// 默认是正常的状态
          entity.setDeviceTimeout(updateDevicePara.getDeviceInfo().getDeviceTimeout());
          deviceInfoService.insert(entity);
        }
      }

      // 请求方没有传设备参数过来，先去数据库找全部的设备
      paraMap = new HashMap<String, Object>();
      paraMap.put("appId", updateDevicePara.getAppId());
      paraMap.put("appSecret", updateDevicePara.getAppSecret());

      paraMap.put("answerTimeout", updateDevicePara.getDeviceInfo().getAnswerTimeout());
      paraMap.put("appendCommand", updateDevicePara.getDeviceInfo().getAppendCommand());
      paraMap.put("debugMode", updateDevicePara.getDeviceInfo().getDebugMode());
      paraMap.put("deviceChannelNum", updateDevicePara.getDeviceInfo().getDeviceChannelNum());
      paraMap.put("devicePassword", updateDevicePara.getDeviceInfo().getDevicePassword());
      paraMap.put("deviceTimeout", updateDevicePara.getDeviceInfo().getDeviceTimeout());
      paraMap.put("heartInterval", updateDevicePara.getDeviceInfo().getHeartInterval());
      paraMap.put("inputChannelIdleStateLevel", updateDevicePara.getDeviceInfo().getInputChannelIdleStateLevel());
      paraMap.put("outConfirmPulseType", updateDevicePara.getDeviceInfo().getOutConfirmPulseType());
      paraMap.put("outPutCoinPulseType", updateDevicePara.getDeviceInfo().getOutPutCoinPulseType());
      paraMap.put("resendMode", updateDevicePara.getDeviceInfo().getResendMode());
      paraMap.put("retryCount", updateDevicePara.getDeviceInfo().getRetryCount());
      paraMap.put("socketMode", updateDevicePara.getDeviceInfo().getSocketMode());
      paraMap.put("gpsCheck", updateDevicePara.getDeviceInfo().getGpsCheck());
      paraMap.put("deviceModelId", updateDevicePara.getDeviceInfo().getDeviceModelId());
      paraMap.put("currentFirmwareVer", updateDevicePara.getDeviceInfo().getHardVer());
      paraMap.put("deviceImeis", list);

      long result = deviceInfoService.updateByMap(paraMap, "updateByDeviceImei");
      log.debug("更新设备参数成功，更新条数：" + result);

      CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.SUCCESS, CommandResult.PublicResultMsg.SUCCESS);
      return JSON.parseObject(commandResult.toString());

    }
    catch (Exception e)
    {
      log.error(e.getMessage(), e);
      // 未知错误
      CommandResult pushResult = new CommandResult(CommandResult.PublicResultCode.UNKNOW_ERROR, CommandResult.PublicResultMsg.UNKNOW_ERROR);
      return JSON.parseObject(pushResult.toString());
    }
  }

  /**
   * 设备初始化的时候，需要更新设备的imei号，mac和sn号，一次只能一个设备。同时更新设备的通道数量和通道明细的内容
   * 
   * @param session
   * @param request
   * @param updateDevicePara
   * @return
   */
  @ResponseBody
  @RequestMapping(value = "/update_device_id.do", method = { RequestMethod.POST })
  public JSONObject updateDeviceId(HttpSession session, HttpServletRequest request, @RequestBody UpdateDevicePara updateDevicePara)
  {
    try
    {
      log.debug("[更新设备信息]收到请求参数：" + updateDevicePara.toString());

      // 校验参数
      HashMap<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("appId", updateDevicePara.getAppId());
      paraMap.put("appSecret", updateDevicePara.getAppSecret());
      List<OrgInfoEntity> orgList = orgInfoService.listByMap(paraMap, "listByAppId");
      if (orgList == null || orgList.size() != 1)
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }
      if (orgList == null || orgList.size() != 1)
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }
      // 判断appid是否合法
      if (!(orgList.get(0).getAppId().equals(updateDevicePara.getAppId()) && orgList.get(0).getAppSecret().equals(updateDevicePara.getAppSecret())))
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }

      String deviceImeis = updateDevicePara.getDeviceImeis();

      if (StringUtils.isEmpty(updateDevicePara.getDeviceInfo()) || StringUtils.isEmpty(updateDevicePara.getDeviceInfo().getDeviceImei()) || StringUtils.isEmpty(updateDevicePara.getDeviceInfo().getDeviceMac()) || StringUtils.isEmpty(updateDevicePara.getDeviceInfo().getDeviceSn()))
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.PARA_ERROR, CommandResult.PublicResultMsg.PARA_ERROR);
        return JSON.parseObject(commandResult.toString());
      }
      
      
      //查看初始化之前的Imei是否存在
      String beforeDeviceImei = updateDevicePara.getBeforeDeviceImei();
      if(beforeDeviceImei!=null){
    	  DeviceInfoEntity beforeDeviceEntity = deviceInfoService.getByKey(beforeDeviceImei);
    	  if(beforeDeviceEntity !=null){
    		  Map<String, Object> paramMap = new HashMap<>();
    		  paramMap.put("deviceImei", beforeDeviceImei);
    		  deviceChannelService.deleteByMap(paramMap, "deleteByMap");
    		  deviceInfoService.deleteByMap(paramMap, "deleteByMap");
          }
      }
      
      
      DeviceInfoEntity entity = deviceInfoService.getByKey(updateDevicePara.getDeviceInfo().getDeviceImei());
      if (entity == null)
      {
        // 如果初始化的时候，没找到这个数据，就新增一条。
        entity = new DeviceInfoEntity();
        entity.setDeviceImei(updateDevicePara.getDeviceInfo().getDeviceImei());
        entity.setDeviceMac(updateDevicePara.getDeviceInfo().getDeviceMac().trim().toUpperCase());
        entity.setDeviceSn(updateDevicePara.getDeviceInfo().getDeviceSn());
        entity.setCreateTime(new Date());
        entity.setDeviceChannelNum(updateDevicePara.getDeviceInfo().getDeviceChannelNum());
        entity.setOrgId(orgList.get(0).getOrgId());
        entity.setAnswerTimeout(10);//应答超时
        entity.setAppendCommand(0);
        entity.setDebugMode(1);
        entity.setDevicePassword(null);
        entity.setHeartInterval(60);//心跳间隔
        entity.setInputChannelIdleStateLevel(1);
        entity.setOutConfirmPulseType(1);
        entity.setOutPutCoinPulseType(1);
        entity.setResendMode(0);//重传方式  0：重传   1：不需重传
        entity.setRetryCount(3);//重传次数
        entity.setSocketMode(0);
        entity.setGpsCheck(1);
        entity.setDeviceModelId(updateDevicePara.getDeviceInfo().getDeviceModelId());// 先设置为空，在参数设置的时候，用户会选择所属的设备类型。这样这个字段就有数据了
        entity.setDeviceStatus(0);// 默认是正常的状态
        entity.setDeviceTimeout(150);// 暂时用不上，因为都是系统配置的统一的超时时间
        entity.setOutSoltNum(0);
        entity.setCurrentFirmwareVer(updateDevicePara.getDeviceInfo().getHardVer());//硬件版本号
        deviceInfoService.insert(entity);

        // 同时新增设备对应的通道数据
        for (int i = 0; i < updateDevicePara.getDeviceInfo().getDeviceChannelNum(); i++)
        {
          DeviceChannelEntity channelEntity = new DeviceChannelEntity();
          channelEntity.setCreateTime(new Date());

          // 生成设备二维码，因为传过来的时候，没有送通道的参数过来，因此只能自己去生成
          String deviceCode = EncryptHelper.encryptEnCodeFor62(updateDevicePara.getDeviceInfo().getDeviceId() + ",0");
          deviceCode = "https://sub-api.8zao.net/device/" + deviceCode;

          channelEntity.setDeviceChannelCode(deviceCode);// 默认情况下设备的二维码信息
          channelEntity.setDeviceChannelId(i);
          channelEntity.setDeviceChannelStatus(0);
          channelEntity.setDeviceImei(updateDevicePara.getDeviceInfo().getDeviceImei());
          channelEntity.setDeviceLockMode(0);// 默认不支持预约功能
          channelEntity.setDeviceLockTime(600);
          deviceChannelService.insert(channelEntity);
        }
        log.debug("新增设备参数成功。>>>>>>>>" + entity.toString());
      }
      else
      {
        // 更新这些参数
        paraMap = new HashMap<String, Object>();
        paraMap.put("appId", updateDevicePara.getAppId());
        paraMap.put("appSecret", updateDevicePara.getAppSecret());

        paraMap.put("deviceImei", updateDevicePara.getDeviceInfo().getDeviceImei());
        paraMap.put("deviceMac", updateDevicePara.getDeviceInfo().getDeviceMac().trim().toUpperCase());
        paraMap.put("deviceSn", updateDevicePara.getDeviceInfo().getDeviceSn());
        paraMap.put("deviceChannelNum", updateDevicePara.getDeviceInfo().getDeviceChannelNum());
        paraMap.put("deviceModelId", updateDevicePara.getDeviceInfo().getDeviceModelId());
        paraMap.put("currentFirmwareVer", updateDevicePara.getDeviceInfo().getHardVer());
        
        paraMap.put("answerTimeout", 10);
        paraMap.put("heartInterval", 60);
        paraMap.put("deviceTimeout", 150);
        paraMap.put("resendMode", 0);
        paraMap.put("retryCount", 3);
        long result = deviceInfoService.updateByMap(paraMap, "updateByDeviceId");
        log.debug("更新设备参数:"+ paraMap +"，更新条数：>>>>>>" + result);

        if (updateDevicePara.getDeviceInfo().getDeviceChannelNum() < entity.getDeviceChannelNum())
        {
          // 如果新修改的数据，小于原来的数据，就把多余的停用
          for (int i = updateDevicePara.getDeviceInfo().getDeviceChannelNum(); i < entity.getDeviceChannelNum(); i++)
          {
            HashMap<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("deviceChannelStatus", 1);
            paramMap.put("deviceImei", updateDevicePara.getDeviceInfo().getDeviceImei());
            paramMap.put("deviceChannelId", i);
            deviceChannelService.updateByMap(paramMap, "updateStatus");
            log.debug("停用多余的设备通道成功，参数：" + paramMap);
          }
        }
        if (updateDevicePara.getDeviceInfo().getDeviceChannelNum() > entity.getDeviceChannelNum())
        {
          // 如果新的数据，比原来的通道数量多，则表示改多了。
          for (int i = entity.getDeviceChannelNum(); i < updateDevicePara.getDeviceInfo().getDeviceChannelNum(); i++)
          {
            // 先查要线增的通道在不在，在就更新，不再就新增
            HashMap<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("deviceImei", updateDevicePara.getDeviceInfo().getDeviceImei());
            paramMap.put("deviceChannelId", i);
            DeviceChannelEntity channelEntity = deviceChannelService.getByMap(paramMap);
            if (channelEntity == null)
            {
              // 如果不存在就新增
              channelEntity = new DeviceChannelEntity();
              channelEntity.setCreateTime(new Date());
              // 生成设备二维码，因为传过来的时候，没有送通道的参数过来，因此只能自己去生成
              String deviceCode = EncryptHelper.encryptEnCodeFor62(updateDevicePara.getDeviceInfo().getDeviceId() + ",0");
              deviceCode = "https://sub-api.8zao.net/device/" + deviceCode;
              channelEntity.setDeviceChannelCode(deviceCode);// 默认情况下没有设备的二维码信息
              channelEntity.setDeviceChannelId(i);
              channelEntity.setDeviceChannelStatus(0);
              channelEntity.setDeviceImei(updateDevicePara.getDeviceInfo().getDeviceImei());
              channelEntity.setDeviceLockMode(0);// 默认不支持预约功能
              channelEntity.setDeviceLockTime(600);
              deviceChannelService.insert(channelEntity);
              log.debug("新增设备通道成功，参数：" + channelEntity.toString());
            }
            else
            {
              // 如果存在就更新状态为可用
              paramMap = new HashMap<String, Object>();
              paramMap.put("deviceChannelStatus", 0);
              paramMap.put("deviceImei", updateDevicePara.getDeviceInfo().getDeviceImei());
              paramMap.put("deviceChannelId", i);
              deviceChannelService.updateByMap(paramMap, "updateStatus");
              log.debug("启用设备通道成功，参数：" + paramMap);
            }
          }
        }
      }

      CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.SUCCESS, CommandResult.PublicResultMsg.SUCCESS);
      return JSON.parseObject(commandResult.toString());
    }
    catch (Exception e)
    {
      log.error(e.getMessage(), e);
      // 未知错误
      CommandResult pushResult = new CommandResult(CommandResult.PublicResultCode.UNKNOW_ERROR, CommandResult.PublicResultMsg.UNKNOW_ERROR);
      return JSON.parseObject(pushResult.toString());
    }
  }
  
  
  
 /* @ResponseBody
  @RequestMapping(value = "/update_device_id.do", method = { RequestMethod.POST })
  public JSONObject updateDeviceId(HttpSession session, HttpServletRequest request, @RequestBody UpdateDevicePara updateDevicePara)
  {
    try
    {
      log.debug("[更新设备信息]收到请求参数：" + updateDevicePara.toString());

      // 校验参数
      HashMap<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("appId", updateDevicePara.getAppId());
      paraMap.put("appSecret", updateDevicePara.getAppSecret());
      List<OrgInfoEntity> orgList = orgInfoService.listByMap(paraMap, "listByAppId");
      if (orgList == null || orgList.size() != 1)
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }
      if (orgList == null || orgList.size() != 1)
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }
      // 判断appid是否合法
      if (!(orgList.get(0).getAppId().equals(updateDevicePara.getAppId()) && orgList.get(0).getAppSecret().equals(updateDevicePara.getAppSecret())))
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }

      String deviceImeis = updateDevicePara.getDeviceImeis();

      if (StringUtils.isEmpty(updateDevicePara.getDeviceInfo()) || StringUtils.isEmpty(updateDevicePara.getDeviceInfo().getDeviceImei()) || StringUtils.isEmpty(updateDevicePara.getDeviceInfo().getDeviceMac()) || StringUtils.isEmpty(updateDevicePara.getDeviceInfo().getDeviceSn()))
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.PARA_ERROR, CommandResult.PublicResultMsg.PARA_ERROR);
        return JSON.parseObject(commandResult.toString());
      }
      
      DeviceInfoEntity entity = deviceInfoService.getByKey(updateDevicePara.getDeviceInfo().getDeviceImei());
      if (entity == null)
      {
        // 如果初始化的时候，没找到这个数据，就新增一条。
        entity = new DeviceInfoEntity();
        entity.setDeviceImei(updateDevicePara.getDeviceInfo().getDeviceImei());
        entity.setDeviceMac(updateDevicePara.getDeviceInfo().getDeviceMac().trim().toUpperCase());
        entity.setDeviceSn(updateDevicePara.getDeviceInfo().getDeviceSn());
        entity.setCreateTime(new Date());
        entity.setDeviceChannelNum(updateDevicePara.getDeviceInfo().getDeviceChannelNum());
        entity.setOrgId(orgList.get(0).getOrgId());
        entity.setAnswerTimeout(5);
        entity.setAppendCommand(0);
        entity.setDebugMode(1);
        entity.setDevicePassword(null);
        entity.setHeartInterval(120);
        entity.setInputChannelIdleStateLevel(1);
        entity.setOutConfirmPulseType(1);
        entity.setOutPutCoinPulseType(1);
        entity.setResendMode(1);
        entity.setRetryCount(5);
        entity.setSocketMode(0);
        entity.setGpsCheck(1);
        entity.setDeviceModelId(updateDevicePara.getDeviceInfo().getDeviceModelId());// 先设置为空，在参数设置的时候，用户会选择所属的设备类型。这样这个字段就有数据了
        entity.setDeviceStatus(0);// 默认是正常的状态
        entity.setDeviceTimeout(180);// 暂时用不上，因为都是系统配置的统一的超时时间
        deviceInfoService.insert(entity);

        // 同时新增设备对应的通道数据
        for (int i = 0; i < updateDevicePara.getDeviceInfo().getDeviceChannelNum(); i++)
        {
          DeviceChannelEntity channelEntity = new DeviceChannelEntity();
          channelEntity.setCreateTime(new Date());

          // 生成设备二维码，因为传过来的时候，没有送通道的参数过来，因此只能自己去生成
          String deviceCode = EncryptHelper.encryptEnCodeFor62(updateDevicePara.getDeviceInfo().getDeviceId() + ",0");
          deviceCode = "https://sub-api.8zao.net/device/" + deviceCode;

          channelEntity.setDeviceChannelCode(deviceCode);// 默认情况下设备的二维码信息
          channelEntity.setDeviceChannelId(i);
          channelEntity.setDeviceChannelStatus(0);
          channelEntity.setDeviceImei(updateDevicePara.getDeviceInfo().getDeviceImei());
          channelEntity.setDeviceLockMode(0);// 默认不支持预约功能
          channelEntity.setDeviceLockTime(600);
          deviceChannelService.insert(channelEntity);
        }
        log.debug("新增设备参数成功。" + entity.toString());
      }
      else
      {
        // 更新这些参数
        paraMap = new HashMap<String, Object>();
        paraMap.put("appId", updateDevicePara.getAppId());
        paraMap.put("appSecret", updateDevicePara.getAppSecret());

        paraMap.put("deviceImei", updateDevicePara.getDeviceInfo().getDeviceImei());
        paraMap.put("deviceMac", updateDevicePara.getDeviceInfo().getDeviceMac().trim().toUpperCase());
        paraMap.put("deviceSn", updateDevicePara.getDeviceInfo().getDeviceSn());
        paraMap.put("deviceChannelNum", updateDevicePara.getDeviceInfo().getDeviceChannelNum());
        paraMap.put("deviceModelId", updateDevicePara.getDeviceInfo().getDeviceModelId());

        long result = deviceInfoService.updateByMap(paraMap, "updateByDeviceId");
        log.debug("更新设备参数成功，更新条数：" + result);

        if (updateDevicePara.getDeviceInfo().getDeviceChannelNum() < entity.getDeviceChannelNum())
        {
          // 如果新修改的数据，小于原来的数据，就把多余的停用
          for (int i = updateDevicePara.getDeviceInfo().getDeviceChannelNum(); i < entity.getDeviceChannelNum(); i++)
          {
            HashMap<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("deviceChannelStatus", 1);
            paramMap.put("deviceImei", updateDevicePara.getDeviceInfo().getDeviceImei());
            paramMap.put("deviceChannelId", i);
            deviceChannelService.updateByMap(paramMap, "updateStatus");
            log.debug("停用多余的设备通道成功，参数：" + paramMap);
          }
        }
        if (updateDevicePara.getDeviceInfo().getDeviceChannelNum() > entity.getDeviceChannelNum())
        {
          // 如果新的数据，比原来的通道数量多，则表示改多了。
          for (int i = entity.getDeviceChannelNum(); i < updateDevicePara.getDeviceInfo().getDeviceChannelNum(); i++)
          {
            // 先查要线增的通道在不在，在就更新，不再就新增
            HashMap<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("deviceImei", updateDevicePara.getDeviceInfo().getDeviceImei());
            paramMap.put("deviceChannelId", i);
            DeviceChannelEntity channelEntity = deviceChannelService.getByMap(paramMap);
            if (channelEntity == null)
            {
              // 如果不存在就新增
              channelEntity = new DeviceChannelEntity();
              channelEntity.setCreateTime(new Date());
              // 生成设备二维码，因为传过来的时候，没有送通道的参数过来，因此只能自己去生成
              String deviceCode = EncryptHelper.encryptEnCodeFor62(updateDevicePara.getDeviceInfo().getDeviceId() + ",0");
              deviceCode = "https://sub-api.8zao.net/device/" + deviceCode;
              channelEntity.setDeviceChannelCode(deviceCode);// 默认情况下没有设备的二维码信息
              channelEntity.setDeviceChannelId(i);
              channelEntity.setDeviceChannelStatus(0);
              channelEntity.setDeviceImei(updateDevicePara.getDeviceInfo().getDeviceImei());
              channelEntity.setDeviceLockMode(0);// 默认不支持预约功能
              channelEntity.setDeviceLockTime(600);
              deviceChannelService.insert(channelEntity);
              log.debug("新增设备通道成功，参数：" + channelEntity.toString());
            }
            else
            {
              // 如果存在就更新状态为可用
              paramMap = new HashMap<String, Object>();
              paramMap.put("deviceChannelStatus", 0);
              paramMap.put("deviceImei", updateDevicePara.getDeviceInfo().getDeviceImei());
              paramMap.put("deviceChannelId", i);
              deviceChannelService.updateByMap(paramMap, "updateStatus");
              log.debug("启用设备通道成功，参数：" + paramMap);
            }
          }
        }
      }

      CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.SUCCESS, CommandResult.PublicResultMsg.SUCCESS);
      return JSON.parseObject(commandResult.toString());
    }
    catch (Exception e)
    {
      log.error(e.getMessage(), e);
      // 未知错误
      CommandResult pushResult = new CommandResult(CommandResult.PublicResultCode.UNKNOW_ERROR, CommandResult.PublicResultMsg.UNKNOW_ERROR);
      return JSON.parseObject(pushResult.toString());
    }
  }*/

  /**
   * 更新设备的通道信息，可以一次性改一批设备的相同通道信息
   * 
   * @param session
   * @param request
   * @param updateDevicePara
   * @return
   */
  @ResponseBody
  @RequestMapping(value = "/update_device_channel_para.do", method = { RequestMethod.POST })
  public JSONObject updateDeviceChannel(HttpSession session, HttpServletRequest request, @RequestBody UpdateDevicePara updateDevicePara)
  {
    try
    {
      log.debug("[更新设备通道信息]收到请求参数：" + updateDevicePara.toString());

      // 校验参数
      HashMap<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("appId", updateDevicePara.getAppId());
      paraMap.put("appSecret", updateDevicePara.getAppSecret());
      List<OrgInfoEntity> orgList = orgInfoService.listByMap(paraMap, "listByAppId");
      if (orgList == null || orgList.size() != 1)
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }
      if (orgList == null || orgList.size() != 1)
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }
      // 判断appid是否合法
      if (!(orgList.get(0).getAppId().equals(updateDevicePara.getAppId()) && orgList.get(0).getAppSecret().equals(updateDevicePara.getAppSecret())))
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }

      String deviceImeis = updateDevicePara.getDeviceImeis();

      if (StringUtils.isEmpty(deviceImeis))
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.PARA_ERROR, CommandResult.PublicResultMsg.PARA_ERROR);
        return JSON.parseObject(commandResult.toString());
      }

      String[] imeiArray = deviceImeis.split(",");
      for (int i = 0; i < imeiArray.length; i++)
      {
        String deviceImei = imeiArray[i];
        if (StringUtils.isEmpty(deviceImei))
        {
          continue;
        }

        // 更新这些参数
        paraMap = new HashMap<String, Object>();
        paraMap.put("appId", updateDevicePara.getAppId());
        paraMap.put("appSecret", updateDevicePara.getAppSecret());

        paraMap.put("deviceImei", deviceImei);
        paraMap.put("deviceChannelId", updateDevicePara.getDeviceChannelEntity().getDeviceChannelId());
        
        // 生成设备二维码，因为批量改的时候，没办法送二维码信息过来，因此只能自己去生成
        String deviceCode = EncryptHelper.encryptEnCodeFor62(updateDevicePara.getDeviceChannelEntity().getDeviceId() + ",0");
        deviceCode = "https://sub-api.8zao.net/device/" + deviceCode;
        
        paraMap.put("deviceChannelCode", deviceCode);
        paraMap.put("deviceChannelStatus", updateDevicePara.getDeviceChannelEntity().getDeviceChannelStatus());
        paraMap.put("deviceLockMode", updateDevicePara.getDeviceChannelEntity().getDeviceLockMode());
        paraMap.put("deviceLockTime", updateDevicePara.getDeviceChannelEntity().getDeviceLockTime());

        long result = deviceChannelService.updateByMap(paraMap, "updateByDeviceChannel");
        log.debug("更新设备参数成功，更新条数：" + result);
      }

      CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.SUCCESS, CommandResult.PublicResultMsg.SUCCESS);
      return JSON.parseObject(commandResult.toString());
    }
    catch (Exception e)
    {
      log.error(e.getMessage(), e);
      // 未知错误
      CommandResult pushResult = new CommandResult(CommandResult.PublicResultCode.UNKNOW_ERROR, CommandResult.PublicResultMsg.UNKNOW_ERROR);
      return JSON.parseObject(pushResult.toString());
    }
  }
  
  
  /**
   * 把通道数量修改多了，那么就新增多的通道，如果多的通道存在，就启用
   * 把通道数量修改少了，那么多余的就自动停用。
   * 
   * @param session
   * @param request
   * @param updateDevicePara
   * @return
   */
  @ResponseBody
  @RequestMapping(value = "/update_device_channel_new.do", method = { RequestMethod.POST })
  public JSONObject updateDeviceChannelNew(HttpSession session, HttpServletRequest request, @RequestBody JSONObject jsonObject)
  {
    try
    {
      log.debug("[新增或修改设备通道信息]收到请求参数：" + jsonObject.toString());

      // 校验参数
      HashMap<String, Object> paraMap = new HashMap<String, Object>();
      paraMap.put("appId", jsonObject.get("appId"));
      paraMap.put("appSecret", jsonObject.get("appSecret"));
      List<OrgInfoEntity> orgList = orgInfoService.listByMap(paraMap, "listByAppId");
      if (orgList == null || orgList.size() != 1)
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }
      if (orgList == null || orgList.size() != 1)
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }
      // 判断appid是否合法
      if (!(orgList.get(0).getAppId().equals(jsonObject.get("appId")) && orgList.get(0).getAppSecret().equals(jsonObject.get("appSecret"))))
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.AUTHENTICATION_ERROR, CommandResult.PublicResultMsg.AUTHENTICATION_ERROR);
        return JSON.parseObject(commandResult.toString());
      }

      String deviceImeis = jsonObject.get("deviceImeis").toString();

      if (StringUtils.isEmpty(deviceImeis))
      {
        CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.PARA_ERROR, CommandResult.PublicResultMsg.PARA_ERROR);
        return JSON.parseObject(commandResult.toString());
      }
      String[] deviceIdArray={};
      if(jsonObject.get("deviceIds")!="" && jsonObject.get("deviceIds")!=null){
    	  deviceIdArray=jsonObject.get("deviceIds").toString().split(",");
      }
      String[] imeiArray = deviceImeis.split(",");
      Integer deviceChannelNum=Integer.valueOf(jsonObject.get("deviceChannelNum").toString());
      Integer deviceLockMode=Integer.valueOf(jsonObject.get("deviceLockMode").toString());
      Integer deviceLockTime=Integer.valueOf(jsonObject.get("deviceLockTime").toString());
      for (int i = 0; i < imeiArray.length; i++)
      {
        String deviceImei = imeiArray[i];
        if (StringUtils.isEmpty(deviceImei))
        {
          continue;
        }
        
        DeviceInfoEntity deviceInfoEntity = deviceInfoService.getByKey(deviceImei);
        if(deviceInfoEntity==null){
        	continue;
        }
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("deviceChannelNum",deviceChannelNum);
        paramMap.put("deviceImei",deviceImei);
        deviceInfoService.updateByMap(paramMap, "updateDeviceChannelNum");
        // 生成设备二维码，因为批量改的时候，没办法送二维码信息过来，因此只能自己去生成
        String deviceCode="";
        if(!StringUtils.isEmpty(deviceIdArray) && deviceIdArray.length!=0){
        	deviceCode = "https://sub-api.8zao.net/device/" + EncryptHelper.encryptEnCodeFor62(deviceIdArray[i]+ ",0");
        }else{
        	paramMap = new HashMap<String, Object>();
			paramMap.put("deviceImei", deviceImei);
			paramMap.put("deviceChannelId", 0);
			DeviceChannelEntity deviceChannelEntity = deviceChannelService.getByMap(paramMap);
			if(deviceChannelEntity==null){
				continue;
			}
			deviceCode=deviceChannelEntity.getDeviceChannelCode();
        }
        // 如果批量修改时，没有输入新的数量，则跳过
		if (deviceChannelNum == null) {
			continue;
		}
        if (deviceChannelNum < deviceInfoEntity.getDeviceChannelNum()) {
			// 把通道数量修改少了，那么多余的就自动停用。
			for (int j = deviceChannelNum; j < deviceInfoEntity.getDeviceChannelNum(); j++) {
				paramMap = new HashMap<String, Object>();
				paramMap.put("deviceChannelStatus",1);
				paramMap.put("deviceImei", deviceImei);
				paramMap.put("deviceChannelId", j);
				deviceChannelService.updateByMap(paramMap, "updateDeviceStatus");
			}
		}
		if (deviceInfoEntity.getDeviceChannelNum() < deviceChannelNum) {
	        Date nowDate = new Date();
			// 把通道数量修改多了，那么就新增多的通道，如果多的通道存在，就启用
			for (int j = deviceInfoEntity.getDeviceChannelNum(); j < deviceChannelNum; j++) {
				paramMap = new HashMap<String, Object>();
				paramMap.put("deviceImei", deviceImei);
				paramMap.put("deviceChannelId", j);
				DeviceChannelEntity deviceChannelEntity = deviceChannelService.getByMap(paramMap);
				if (deviceChannelEntity == null) {
					DeviceChannelEntity channelEntity = new DeviceChannelEntity();
					channelEntity.setDeviceImei(deviceImei);
					channelEntity.setDeviceChannelId(j);
					channelEntity.setDeviceChannelCode(deviceCode);
					channelEntity.setCreateTime(nowDate);
					channelEntity.setDeviceChannelStatus(0);
					channelEntity.setDeviceLockMode(deviceLockMode);
					channelEntity.setDeviceLockTime(deviceLockTime);
					deviceChannelService.insert(channelEntity);
				} else {
					paramMap = new HashMap<String, Object>();
					paramMap.put("deviceChannelStatus", "0");
					paramMap.put("deviceImei", deviceImei);
					paramMap.put("deviceChannelId", j);
					deviceChannelService.updateByMap(paramMap, "updateDeviceStatus");
				}
			}
		}
      }

      CommandResult commandResult = new CommandResult(CommandResult.PublicResultCode.SUCCESS, CommandResult.PublicResultMsg.SUCCESS);
      return JSON.parseObject(commandResult.toString());
    }
    catch (Exception e)
    {
      log.error(e.getMessage(), e);
      // 未知错误
      CommandResult pushResult = new CommandResult(CommandResult.PublicResultCode.UNKNOW_ERROR, CommandResult.PublicResultMsg.UNKNOW_ERROR);
      return JSON.parseObject(pushResult.toString());
    }
  }
}
